package com.example.hibernate.utils;

import java.util.List;

import com.example.customutils.StringUtils;
import com.example.utils.Constants;

public class QueryBuilder {

	public static String buildWhereClause(String whereClause, List<Object> params){
		if(StringUtils.count(whereClause, Constants.WHERECLAUSE_PARAMETER) != params.size())
			return whereClause;
		
		for(int i=0; i<params.size();i++){
			int paramIndex = whereClause.indexOf(Constants.WHERECLAUSE_PARAMETER);
			Object o = params.get(i);
			if(o instanceof Integer)
				whereClause = replaceWithInteger(whereClause, (Integer)o, paramIndex);
			if(o instanceof String)
				whereClause = replaceWithString(whereClause, (String)o, paramIndex);
		}
		
		return whereClause;
	}
	
	private static String replaceWithString(String whereClause, String str, int index) {
		StringBuffer sb = new StringBuffer();
		sb.append(whereClause.substring(0, index));
		if((whereClause.substring(index+1, index+2).equalsIgnoreCase(Constants.SINGLE_QUOTE)) && (whereClause.substring(index-1, index).equalsIgnoreCase(Constants.SINGLE_QUOTE)) )
			sb.append(str);
		else
			sb.append("\'" + str + "\'");
		sb.append(whereClause.substring(index+1, whereClause.length()));
		return sb.toString();
	}

	public static String replaceWithInteger(String whereClause, Integer value, int index){
		StringBuffer sb = new StringBuffer();
		sb.append(whereClause.substring(0, index));
		sb.append("" + value);
		sb.append(whereClause.substring(index+1, whereClause.length()));
		return sb.toString();
	}
	
//	public static void main(String[] args) {
//		List l = new ArrayList();
//		l.add("Viswanath");
//		l.add(new Integer(10));
//		l.add("Hosur");
//		System.out.println(QueryBuilder.buildWhereClause("My Name is ? and i am ? years young, and i am from '?'", l));
//	}
}
